package cn.harry.cabinet.utils

import android.content.Context
import android.media.AudioManager
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import java.util.*

/**
 * TTS语音播报管理器（简化版）
 * 支持离线使用，兼容Android 5.1系统
 */
class TTSManager private constructor(private val context: Context) : TextToSpeech.OnInitListener {

    companion object {
        private const val TAG = "TTSManager"
        private var instance: TTSManager? = null

        /**
         * 获取单例实例
         */
        fun getInstance(context: Context): TTSManager {
            return instance ?: synchronized(this) {
                instance ?: TTSManager(context.applicationContext).also { instance = it }
            }
        }
    }

    private var textToSpeech: TextToSpeech? = null
    private var isInitialized = false
    private var initializationCallback: ((Boolean) -> Unit)? = null
    private var audioManager: AudioManager? = null

    // 语速设置（默认1.0倍速）
    private var speechRate: Float = 1.0f

    /**
     * 初始化TTS
     */
    fun initialize(callback: ((Boolean) -> Unit)? = null) {
        initializationCallback = callback
        try {
            audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            textToSpeech = TextToSpeech(context, this)
        } catch (e: Exception) {
            Log.e(TAG, "TTS初始化失败: ${e.message}")
            callback?.invoke(false)
        }
    }

    /**
     * TTS初始化回调
     */
    override fun onInit(status: Int) {
        if (status == TextToSpeech.SUCCESS) {
            textToSpeech?.let { tts ->
                // 尝试设置中文语言
                var languageSet = false
                
                // 检查中文语言支持
                val chineseLocales = arrayOf(
                    Locale.SIMPLIFIED_CHINESE,
                    Locale.CHINA,
                    Locale("zh", "CN")
                )

                for (locale in chineseLocales) {
                    val result = tts.setLanguage(locale)
                    if (result == TextToSpeech.LANG_AVAILABLE ||
                        result == TextToSpeech.LANG_COUNTRY_AVAILABLE ||
                        result == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE
                    ) {
                        Log.i(TAG, "成功设置中文语音: ${locale.displayName}")
                        languageSet = true
                        break
                    }
                }

                // 如果中文不支持，使用系统默认语言
                if (!languageSet) {
                    Log.w(TAG, "中文语音不支持，使用系统默认语言")
                    tts.setLanguage(Locale.getDefault())
                }

                // 设置语音参数
                tts.setSpeechRate(speechRate)
                tts.setPitch(1.0f)

                // 设置播放监听器
                tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
                    override fun onStart(utteranceId: String?) {
                        Log.d(TAG, "开始播放语音: $utteranceId")
                    }

                    override fun onDone(utteranceId: String?) {
                        Log.d(TAG, "语音播放完成: $utteranceId")
                    }

                    override fun onError(utteranceId: String?) {
                        Log.e(TAG, "语音播放出错: $utteranceId")
                    }
                })

                isInitialized = true
                Log.i(TAG, "TTS初始化成功")
                initializationCallback?.invoke(true)
            }
        } else {
            Log.e(TAG, "TTS初始化失败，状态码: $status")
            isInitialized = false
            initializationCallback?.invoke(false)
        }
    }

    /**
     * 播放语音
     * @param text 要播放的文本
     * @param utteranceId 播放ID
     * @param interrupt 是否打断当前播放
     */
    fun speak(text: String, utteranceId: String = "default", interrupt: Boolean = true) {
        if (!isInitialized) {
            Log.w(TAG, "TTS未初始化，无法播放语音")
            return
        }

        if (text.isBlank()) {
            Log.w(TAG, "播放文本为空")
            return
        }

        textToSpeech?.let { tts ->
            try {
                // 如果需要打断，先停止当前播放
                if (interrupt) {
                    tts.stop()
                }

                val queueMode = if (interrupt) TextToSpeech.QUEUE_FLUSH else TextToSpeech.QUEUE_ADD

                val result = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    // Android 5.0及以上使用新API
                    val params = Bundle().apply {
                        putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC)
                        putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1.0f)
                    }
                    tts.speak(text, queueMode, params, utteranceId)
                } else {
                    // Android 5.0以下使用旧API
                    val params = HashMap<String, String>().apply {
                        put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId)
                        put(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC.toString())
                    }
                    @Suppress("DEPRECATION")
                    tts.speak(text, queueMode, params)
                }

                if (result == TextToSpeech.SUCCESS) {
                    Log.d(TAG, "播放语音: $text")
                } else {
                    Log.e(TAG, "播放语音失败，错误码: $result")
                }
            } catch (e: Exception) {
                Log.e(TAG, "播放语音异常: ${e.message}")
            }
        }
    }

    /**
     * 停止TTS播放
     */
    fun stop() {
        textToSpeech?.stop()
    }

    /**
     * 检查TTS是否正在播放
     */
    fun isSpeaking(): Boolean {
        return textToSpeech?.isSpeaking ?: false
    }

    /**
     * 检查TTS是否已初始化
     */
    fun isInitialized(): Boolean {
        return isInitialized
    }

    /**
     * 设置语速
     * @param rate 语速倍率（0.5 - 2.0）
     */
    fun setSpeechRate(rate: Float) {
        speechRate = rate.coerceIn(0.5f, 2.0f)
        textToSpeech?.setSpeechRate(speechRate)
    }

    /**
     * 释放资源
     */
    fun shutdown() {
        try {
            textToSpeech?.stop()
            textToSpeech?.shutdown()
            textToSpeech = null
            isInitialized = false
            Log.i(TAG, "TTS资源已释放")
        } catch (e: Exception) {
            Log.e(TAG, "释放TTS资源失败: ${e.message}")
        }
    }
}
